package com.bwie.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.UserLoginVo;
import com.bwie.vo.UserPageInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
* @author 叶雨洁
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2025-07-17 18:48:15
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{


    @Autowired
    TbUserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public R userList(UserPageInfoVo userPageInfoVo) {


        Page<TbUser> tbUserPage = new Page<>(userPageInfoVo.getPageNum(),userPageInfoVo.getPageSize());

        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        Page<TbUser> tbUserPage1 = userMapper.selectPage(tbUserPage, queryWrapper);
        return R.OK(tbUserPage1);
    }

    @Override
    public R sendCode(UserLoginVo userLoginVo) {
        //校验手机号
        boolean mobile = Validator.isMobile(userLoginVo.getUserMobile());
        if(!mobile){
            return R.ERROR(500,"手机号不正确");
        }

        //获取验证码
        String phoneCode = RandomUtil.randomNumbers(4);
        //发送验证码
        MobileMessageUtil.sendMobileMessage(userLoginVo.getUserMobile(), phoneCode);
        System.out.println("发送成功，验证码是"+phoneCode);

        String key="code-"+userLoginVo.getUserMobile();

        redisTemplate.opsForValue().set(key,phoneCode,15, TimeUnit.MINUTES);

        return R.OK();
    }

    @Override
    public R regire(UserLoginVo userLoginVo) {


        //判断用户是否存在
        TbUser tbUser = userMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, userLoginVo.getUserMobile())
        );
        if(tbUser!=null){
            return R.ERROR(500,"用户已存在,请进行登录");
        }
        //获取验证码
        String key="code-"+userLoginVo.getUserMobile();
        String phoneCode = redisTemplate.opsForValue().get(key);
        //判断验证码
        if(phoneCode==null){
            return R.ERROR(500,"验证码失效");
        }
        if(!phoneCode.equals(userLoginVo.getPhoneCode())){
            return R.ERROR(500,"验证码错误");
        }
        //使用crypt加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(userLoginVo.getUserPass());

        //进行注册
        TbUser tbUser1 = new TbUser();
        tbUser1.setUserMobile(userLoginVo.getUserMobile());
        tbUser1.setUserPass(encode);

        userMapper.insert(tbUser1);
        return R.OK();
    }

    @Override
    public R userLogin(UserLoginVo userLoginVo) {

        TbUser tbUser = userMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, userLoginVo.getUserMobile())
        );
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(tbUser==null){
            return R.ERROR(500,"用户不存在");
        }
        boolean matches = encoder.matches(userLoginVo.getUserPass(),tbUser.getUserPass());
        if(!matches){
            return R.ERROR(500,"密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userId", tbUser.getUserId())
                .claim("userPass",tbUser.getUserPass()).claim("userMobile",tbUser.getUserMobile())
                .compact();
        String key="token-"+tbUser.getUserId();
        redisTemplate.opsForValue().set(key,token);

        String roleName = userMapper.selectRole(tbUser.getUserId());
        tbUser.setRoleName(roleName);
        tbUser.setToken(token);


        // Jedis jedis = new Jedis("localhost", 6379);

        return R.OK(tbUser);

    }







}




